package com.atguigu.guli.service.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.guli.service.oss.service.FileService;
import com.atguigu.guli.service.oss.util.OssProperties;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author lsystart
 * @create2021-10-30 11:05
 */

@Service
public class FileServiceImpl implements FileService {

    @Resource
    OssProperties ossProperties;

    String endpoint;
    String accessKeyId;
    String accessKeySecret;
    String bucketName;

    @PostConstruct
    public void init() {
        endpoint = ossProperties.getEndpoint();
        accessKeyId = ossProperties.getAccessKeyId();
        accessKeySecret = ossProperties.getAccessKeySecret();
        bucketName = ossProperties.getBucketName();
    }

    @Override
    public String upload(InputStream inputStream, String originalFilename, String dirName) {


        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String time = new DateTime().toString("yyyy/MM/dd/");
        String fileName = dirName + "/" + time + UUID.randomUUID().toString().replace("-", "")
                + originalFilename.substring(originalFilename.lastIndexOf("."));
        //上传
        ossClient.putObject(bucketName, fileName, inputStream);
        //关闭资源
        ossClient.shutdown();
        String fileURL = "http://" + bucketName + "." + endpoint + "/" + fileName;
        return fileURL;
    }

    @Override
    public void delete(String fileURL, String module) {
        String objectName = fileURL.substring(fileURL.lastIndexOf(module));
//        String objectName = "avatar/2021/10/31/ed493fde6bc74ed4992703eecfc0679a.jpg";
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject(bucketName, objectName);
        ossClient.shutdown();
    }
}
